#!/usr/bin/python
# -*- coding: utf-8 -*-
# Create Time :  2007-1-16 下午10:22:10

from LicManager import models
from django import http
from django import newforms as forms
from django.shortcuts import render_to_response
from django.template.context import Context
import types
import uuid


def remove_slash( s ):
    if type( s ) == types.NoneType: 
        return None
    else:
        return s.replace( '/', '' ).replace( '''\\''', '' )
#===============================================================================
#def index(request):
#    '''game loader license manager index page 
#    
#    @param request:
#    '''
#    client_list = models.Client.objects.all()
#
#    index_context = Context({'client_list':client_list, \
#                             'client_ipaddress':get_client_ip(request), \
#                             'current_time':time.ctime()})
#    
#    return render_to_response('licmanager_index.htm', index_context)
#===============================================================================

class Add_regcode_form( forms.Form ):
    '''make a html form code
    '''
    
    reg_code_number = forms.IntegerField()

def view_regcode( request, *args, **kw ):
    '''reg code actions
    
    @param request:
    @param *args:
    @param **kw:
    '''
    
    print args, kw, 'args--,kw--'
    print request.POST, 'POST--'
    print request.GET, 'GET--'
    u_id = args[0]
    
    print u_id, '===='
    # test client id , if not exist , return HTTP 404
    try:
        client_info = models.Client.objects.get( id=u_id )
    except models.Client.DoesNotExist: 
        return http.Http404
    
    form_act = remove_slash( args[1] )

    print form_act, '======'
    
    # check input form
    if form_act == None:
        # return default page 
        regcode_forms = Add_regcode_form()
        regcode_forms.client_name = forms.CharField( initial=client_info.client_name )
        
        # get client regcode list
        client_reg_lists = get_all_regcode_from_client_id( u_id )
        
        client_regcode_number = len( client_reg_lists )
            
        page_context = Context( {'regcode_forms' : regcode_forms, \
                             'client_name': client_info.client_name, \
                             'client_id': u_id, \
                             'client_reg_lists': client_reg_lists, \
                             'client_regcode_number': client_regcode_number} )
        
        return render_to_response( 'licmanager_regcode.htm', page_context )
    
    # check post and get value
    if request.POST == {} and request.GET == {}:
        # return default page
        regcode_forms = Add_regcode_form()
        regcode_forms.client_name = forms.CharField( initial=client_info.client_name )
        
        
        # get client regcode list
        client_reg_lists = get_all_regcode_from_client_id( u_id )
        
        #for x in client_reg_lists:
        #    print x.id, x.client_reg_code
        
        page_context = Context( {'regcode_forms' : regcode_forms, \
                             'client_name' : client_info.client_name, \
                             'client_id' : u_id, \
                             'client_reg_lists' : client_reg_lists, \
                             'client_regcode_number': client_regcode_number} )
        
        return render_to_response( 'licmanager_regcode.htm', page_context )
    else:
        pass
    
    # check form actions
    if form_act == 'changeregcode':
        
        form_args =  request.POST
        print form_args
        
        regid_lists = form_args.getlist( 'regid' )
        edit_action = form_args['editact']
        
        if edit_action == 'Mark Regcode False':
            mark_regcode_false( ri=regid_lists )
            return http.HttpResponseRedirect( '/clic/editregcode/%s/' % u_id )
        
        elif edit_action == 'Mark Regcode True':
            mark_regcode_true( ri=regid_lists )
            return http.HttpResponseRedirect( '/clic/editregcode/%s/' % u_id )
        
        elif edit_action == 'Delete Regcode':
            delete_regcode( ri=regid_lists )
            return http.HttpResponseRedirect( '/clic/editregcode/%s/' % u_id )
        
        elif edit_action == 'Reset Regcode Activation Times':
            reset_Regcode_activation_times( ri=regid_lists )
            return http.HttpResponseRedirect( '/clic/editregcode/%s/' % u_id )
        
        else:
            return http.HttpResponseRedirect( '/clic/editregcode/%s/' % u_id )
        
        return http.HttpResponseRedirect( '/clic/editregcode/%s/' % u_id )
    
    elif form_act == 'addregcode':
        form_args = request.GET
        try:
            reg_code_number = int( form_args['reg_code_number'] )
        except ValueError:
            reg_code_number = 0
            
        # make regcode
        gen_reg_code( u_id, reg_code_number )
        
        #return HttpResponse('addregcode')
        return http.HttpResponseRedirect( '/clic/editregcode/%s/' % u_id )
    
def view_client( request, *args, **kw ):
    '''
    
    @param request:
    @param *args:
    @param **kw:
    '''
    
    print args, kw, 'args--,kw--'
    print request.POST, 'POST--'
    print request.GET, 'GET--'
    u_id = args[0]
    print u_id
    
    # test client id , if not exist , return HTTP 404
    try:
        client_info = models.Client.objects.get( id=u_id )
    except models.Client.DoesNotExist: 
        return http.Http404
    
    try:
        form_act = remove_slash( args[1] )
    except IndexError: 
        form_act = None
    
    print form_act, '--'
    
    page_context = Context( {} )
        
    return render_to_response( 'licmanager_client.htm', page_context )

def view_add_client( request, *args, **kw ):
    pass

def try_to_reset_regcode( ui, ci ):
    '''reset regcode times
    
    @param ui: user id
    @param ci: regcode id
    '''
    
    pass

def get_all_regcode_from_client_id( ci ):
    '''
    
    @param i: client id
    '''
    
    regcode_list = models.LicData.objects.filter( client_id=ci )
    
    return regcode_list

def gen_reg_code( ci, num ):
    '''
    
    @param i: client id
    @param n: make reg code number
    '''
    
    reg_c_id = models.Client.objects.get( id=ci )
    reg_set_times = 0
    reg_stats = True # True for regable, False not Regable
    for x in range( 0, num ):
        reg_code =  uuid.uuid4()
        d = models.LicData( client_id=reg_c_id, \
                           client_reg_stats=reg_stats, \
                           client_reg_code=str( reg_code ), \
                           client_reg_reset_times=reg_set_times )
        d.save()

def make_regcode_false( **kw ):
    '''
    
    @param i: client id
    @param *args: regcode id list
    '''
    
    pass

def delete_regcode( ri ):
    '''
    @param ri: regcode id
    '''
    for x in ri:
        models.LicData.objects.get( id=x ).delete()
        
def mark_regcode_false( ri ):
    '''
    
    @param ri:
    '''
    for x in ri:
        r = models.LicData.objects.get( id=x )
        r.client_reg_stats = False
        r.save()

def mark_regcode_true( ri ):
    '''
    
    @param ri:
    '''
    for x in ri:
        r = models.LicData.objects.get( id=x )
        r.client_reg_stats = True
        r.save()
        
def reset_Regcode_activation_times( ri ):
    '''
    
    @param ri:
    '''
    for x in ri:
        r = models.LicData.objects.get( id=x )
        r.client_reg_reset_times = 0
        r.save()
    

def get_client_ip( request ):
    '''report client connect ipaddress
    
    @param request:
    ''' 
    
    return request.META['REMOTE_ADDR']
